package com.cloud.tool.service;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author WangZY
 * @Date 2021/9/15 11:15
 * @Description mybatis类型转换器
 **/
@Component
public class JasyptMybatisHandler implements TypeHandler<String> {

    /**
     * mybatis-plus需在表实体类上加 @TableName(autoResultMap = true)
     * 属性字段上需加入 @TableField(value = "item_cost", typeHandler = JasyptMybatisHandler.class)
     */
    private final StringEncryptor encryptor;

    public JasyptMybatisHandler(StringEncryptor encryptor) {
        this.encryptor = encryptor;
    }

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
        if (StringUtils.isEmpty(s)) {
            preparedStatement.setString(i, "");
        } else {
            preparedStatement.setString(i, encryptor.encrypt(s.trim()));
        }
    }

    @Override
    public String getResult(ResultSet resultSet, String s) throws SQLException {
        if (StringUtils.isEmpty(resultSet.getString(s))) {
            return resultSet.getString(s);
        } else {
            return encryptor.decrypt(resultSet.getString(s).trim());
        }
    }

    @Override
    public String getResult(ResultSet resultSet, int i) throws SQLException {
        if (StringUtils.isEmpty(resultSet.getString(i))) {
            return resultSet.getString(i);
        } else {
            return encryptor.decrypt(resultSet.getString(i).trim());
        }
    }

    @Override
    public String getResult(CallableStatement callableStatement, int i) throws SQLException {
        if (StringUtils.isEmpty(callableStatement.getString(i))) {
            return callableStatement.getString(i);
        } else {
            return encryptor.decrypt(callableStatement.getString(i).trim());
        }
    }
}